package com.wcl.demo.model;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.util.NetUtils;
import com.wcl.demo.application.BaseApplication;
import com.wcl.demo.model.modelinterface.ModelLoginInterface;
import com.wcl.demo.presenter.presenterinterface.PresenterLoginInterface;
import com.wcl.demo.ui.activity.LoginActivity;
import com.wcl.demo.ui.activity.MainActivity;
import com.wcl.demo.utils.ActivityUtils;
import com.wcl.demo.utils.ProgressUtils;
import com.wcl.demo.view.CustomToast;

import java.util.Map;

/**
 * Created by dllo on 15/11/20.
 */
public class ModelLogin implements ModelLoginInterface {

    public ModelLogin() {

    }

    @Override
    public void startLogin(Map<String, String> map, final PresenterLoginInterface presenterLoginInterface) {

        String loginUsername = map.get("loginUsername");
        String loginPsw = map.get("loginPsw");
        boolean isAutoLogin = false;

        final Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                presenterLoginInterface.sendLoginResult("自动登录开启");
                presenterLoginInterface.sendLoginResult("登陆成功");
                return false;
            }
        });

        boolean network = NetUtils.hasNetwork(BaseApplication.getContext());
        if (network == false && isAutoLogin) {
            handler.sendEmptyMessage(002);
            return;
        }else{

        }

        if (TextUtils.isEmpty(loginUsername)) {
            CustomToast.toastShow(BaseApplication.getContext() , "用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(loginPsw)) {
            CustomToast.toastShow(BaseApplication.getContext() , "密码不能为空");
            return;
        }

        final long start = System.currentTimeMillis();

        EMChatManager.getInstance().login(loginUsername, loginPsw, new EMCallBack() {
            @Override
            public void onSuccess() {
                // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                EMGroupManager.getInstance().loadAllGroups();
                EMChatManager.getInstance().loadAllConversations();
                handler.sendEmptyMessage(002);
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }
}
